package com.valuegroup.smarttodo.ui.programme.curriculum;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.valuegroup.smarttodo.R;
import com.valuegroup.smarttodo.data.ServiceFactory;
import com.valuegroup.smarttodo.data.model.Curriculum;
import com.valuegroup.smarttodo.data.vo.CurriculumEventVo;
import com.valuegroup.smarttodo.ui.BaseActivity;
import com.valuegroup.smarttodo.ui.todo.task.qucikadd.QucikAddActivity;
import com.valuegroup.smarttodo.ui.todo.task.qucikadd.QucikAddInputCheckRule;
import com.valuegroup.smarttodo.ui.todo.task.qucikadd.QuickAddEditorCallback;
import com.valuegroup.smarttodo.ui.todo.task.qucikadd.QuickAddHolder;
import com.valuegroup.smarttodo.plugins.pickdialog.DateUtils;
import com.valuegroup.smarttodo.util.AlertUtils;

import java.io.File;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 学习清单
 */
public class CurriculumOrderActivity extends BaseActivity {

    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.btnBack)
    ImageButton btnBack;
    @BindView(R.id.imgCover)
    ImageView imgCover;
    @BindView(R.id.labTitle)
    TextView labTitle;
    @BindView(R.id.labDate)
    TextView labDate;
    @BindView(R.id.labCount)
    TextView labCount;
    @BindView(R.id.labEventCount)
    TextView labEventCount;
    @BindView(R.id.tagFinish)
    TextView tagFinish;
    @BindView(R.id.recycler)
    RecyclerView recyclerView;

    private Long DATA_ID;
    private Integer DATA_POSITION;
    private Curriculum DATA;
    private CurriculumOrderAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_curriculum_order);
        ButterKnife.bind(this);

        DATA_ID = getIntent().getLongExtra(PARAMS_KEY, 0);
        DATA_POSITION = getIntent().getIntExtra(PARAMS_POSITION, 0);
        DATA = ServiceFactory.getInstance().getCurriculumService().getCurriculumDao().load(DATA_ID);

        if (DATA_ID != 0 && DATA == null) {
            AlertUtils.showToast(getApplicationContext(), R.string.not_found_record);
            finish();
            return;
        }

        if (DATA_ID == 0) {
            DATA = ServiceFactory.getInstance().getCurriculumService().getDefaultCurriculum();
        }

        initView();
        initData();
    }


    private void initData() {
        labTitle.setText(DATA.getTitle());
        labDate.setText(String.format(getResources().getString(R.string.curriculum_time_frame), DateUtils.date2str(DATA.getStartDt(), DateUtils.F30), DateUtils.date2str(DATA.getEndDt(), DateUtils.F30)));
        labCount.setText(String.format(getResources().getString(R.string.curriculum_study_count), DateUtils.dateInterval(DATA.getStartDt(), DATA.getEndDt())));
        tagFinish.setVisibility(DATA.getStudyFinish() ? View.VISIBLE : View.GONE);

        // 设置封面图片
        if (!TextUtils.isEmpty(DATA.getImagePath())) {
            //Uri u = new Uri.Builder().scheme("file").path("//" + DATA.getImagePath()).build();
            //btnSetCover.setVisibility(View.GONE);
            //imgCover.setImageURI(u);

            // 设置圆角图片
            /*RoundedBitmapDrawable roundedBitmapDrawable1 = RoundedBitmapDrawableFactory.create(getResources(),  DATA.getImagePath());
            roundedBitmapDrawable1.setCornerRadius(6);
            imgCover.setImageDrawable(roundedBitmapDrawable1);*/

            RequestOptions options = RequestOptions
                    .bitmapTransform(new RoundedCorners(6)) //设置图片圆角角度
                    .diskCacheStrategy(DiskCacheStrategy.NONE)//不做磁盘缓存
                    .skipMemoryCache(true)//不做内存缓存
                    .placeholder(R.drawable.ic_default_image)//图片加载出来前，显示的图片
                    .fallback(R.drawable.ic_default_image) //url为空的时候,显示的图片
                    .error(R.drawable.ic_default_image);//图片加载失败后，显示的图片

            Uri u = new Uri.Builder().scheme("file").path("//" + DATA.getImagePath()).build();
            Glide.with(this).load(u)
                    .apply(options)
                    .into(imgCover);
        } else {
            //btnSetCover.setVisibility(View.VISIBLE);
            imgCover.setImageResource(R.drawable.ic_default_image);
        }

        loadEventCount();
    }

    private void loadEventCount() {
        int[] countArr = ServiceFactory.getInstance().getCurriculumService().countCurriculumEvent(DATA_ID);
        labEventCount.setText(String.format(getResources().getString(R.string.event_count), countArr[1], countArr[0]));
    }

    private void initView() {

        // 初始化工具条
        setSupportActionBar(toolbar);
        // 隐藏Toolbar的标题栏
        getSupportActionBar().setDisplayShowTitleEnabled(false);

        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        adapter = new CurriculumOrderAdapter(this, recyclerView, DATA_ID);
        recyclerView.setAdapter(adapter);

        adapter.setRefreshEventCountCallback(new CurriculumOrderAdapter.RefreshEventCountCallback() {
            @Override
            public void refresh() {
                loadEventCount();
            }
        });

        ItemTouchHelper mItemTouchHelper = new ItemTouchHelper(new CurriclumTouchHelper(adapter, this));
        mItemTouchHelper.attachToRecyclerView(recyclerView);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_curriculum_order, menu);
        return true;
    }

    @Override
    public boolean onPrepareOptionsMenu(@NonNull Menu menu) {
        menu.findItem(R.id.m5).setTitle(!DATA.getStudyFinish() ? R.string.curriculum_order_m5 : R.string.curriculum_order_m5_o);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.m1:
                /*初始化 浮动在键盘上的快捷输入框*/
                QucikAddActivity.openEditor(
                        this,
                        new QuickAddEditorCallback() {
                            @Override
                            public void onCancel() {
                            }

                            @Override
                            public void onSubmit(String content) {
                                if (TextUtils.isEmpty(content)) {
                                    return;
                                }

                                // 新增内容
                                CurriculumEventVo item = new CurriculumEventVo();
                                item.setPid(DATA_ID);
                                item.setTitle(content);
                                adapter.addItem(adapter.getContentSize(), item);

                                //平滑到新增项
                                recyclerView.smoothScrollToPosition(adapter.getContentSize());

                                loadEventCount();
                            }

                            @Override
                            public void onAttached(final ViewGroup rootView) {
                                // 表情(暂时弃用)
                            }
                        },
                        new QuickAddHolder(QuickAddHolder.QuickAddType.EVENT_INSERT),
                        new QucikAddInputCheckRule(120, 2));

                break;
            case R.id.m2:
                QucikAddActivity.openEditorNoRepeat(
                        this,
                        new QuickAddEditorCallback() {
                            @Override
                            public void onCancel() {
                            }

                            @Override
                            public void onSubmit(String content) {
                                if (TextUtils.isEmpty(content)) {
                                    return;
                                }
                                ServiceFactory.getInstance().getCurriculumService().multiInsert(DATA_ID, content);
                                refreshAllData();
                            }

                            @Override
                            public void onAttached(ViewGroup rootView) {

                            }
                        },
                        new QuickAddHolder(QuickAddHolder.QuickAddType.MULTI_INSERT_FOR_STUDY),
                        new QucikAddInputCheckRule(2000, 2),
                        Gravity.CENTER);
                break;
            case R.id.m3:

                AlertUtils.delOrderDialog(this,
                        String.format(getResources().getString(R.string.alt_reset_curriculum), DATA.getTitle()),
                        (dialog, which) -> {
                            ServiceFactory.getInstance().getCurriculumService().resetCurriculum(DATA.getId());
                            initData();
                            refreshAllData();
                        });

                break;
            case R.id.m4:
                AlertUtils.delOrderDialog(this,
                        String.format(getResources().getString(R.string.alt_del_curriculum), DATA.getTitle()),
                        (dialog, which) -> {

                            if (DATA != null && !TextUtils.isEmpty(DATA.getImagePath())) {
                                File rootDir = new File(DATA.getImagePath());
                                if (rootDir.exists()) {
                                    rootDir.delete();
                                }
                            }

                            ServiceFactory.getInstance().getCurriculumService().delCurriculum(DATA.getId());
                            finishAfterTransition();
                        });
                break;
            case R.id.m5:
                DATA.setStudyFinish(!DATA.getStudyFinish());
                ServiceFactory.getInstance().getCurriculumService().doFinish(DATA.getId(), DATA.getStudyFinish());
                tagFinish.setVisibility(DATA.getStudyFinish() ? View.VISIBLE : View.GONE);
                break;
        }
        return false;
    }

    /**
     * 更新列表所有数据
     */
    private void refreshAllData() {
        // 刷新列表数据
        adapter.refreshListData(DATA_ID, false);
        // 平移到相关位置
        recyclerView.smoothScrollToPosition(0);

        loadEventCount();
    }

    private List<CurriculumEventVo> loadData() {
        DATA_ID = getIntent().getLongExtra(PARAMS_KEY, 0);
        return ServiceFactory.getInstance().getCurriculumService().findCurriculumEventForHome(DATA_ID);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        initData();
        refreshAllData();
    }

    @Override
    public void onBackPressed() {
        setCloseParams();
        super.onBackPressed();
    }

    private void setCloseParams() {
        Intent intent = new Intent();
        intent.putExtra(PARAMS_POSITION, DATA_POSITION);
        intent.putExtra(PARAMS_KEY, DATA_ID);
        setResult(RESULT_OK, intent);
    }


    @OnClick({R.id.btnBack, R.id.btnGoForm})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btnBack:
                setCloseParams();
                finishAfterTransition();
                break;
            case R.id.btnGoForm:
                Intent intent = new Intent(view.getContext(), CurriculumSetActivity.class);
                intent.putExtra(PARAMS_KEY, DATA.getId());
                intent.putExtra(PARAMS_POSITION, DATA_POSITION);
                startActivityForResult(intent, 1001);
                break;
        }
    }

}
